<template>
      <div>
      <el-scrollbar :style="{height: bodyHeight+'px'}">
      <el-form ref="formData" :model="formData" :rules="rules" label-width="125px" class="form-wrap" v-loading="loading" :element-loading-text="loadingText">
        <el-form-item label="Language" prop="locale">
          <el-radio-group v-model="localeName" @change="changeLanguage">
            <el-radio-button name="zh" label="Chinese"></el-radio-button>
            <el-radio-button name="ja" label="Japanese"></el-radio-button>
            <el-radio-button name="en" label="English"></el-radio-button>
          </el-radio-group>

<!--          <el-input v-model="formData.locale" placeholder="Please Select A Language"></el-input>-->
        </el-form-item>
        <el-form-item label="Name"  prop="name">
          <el-input v-model="formData.name" placeholder="Please Enter Name"></el-input>
        </el-form-item>

        <el-form-item label="Summary" prop="summary">
          <el-input
            type="textarea"
            placeholder="Please Enter Summary"
            v-model="formData.summary"
            rows="8"
            maxlength="1000"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="Space" prop="space">
          <el-input
            type="textarea"
            placeholder="Please Enter Space"
            v-model="formData.space"
            rows="8"
            maxlength="1000"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="Access" prop="access">
          <el-input
            type="textarea"
            placeholder="Please Enter Access"
            v-model="formData.access"
            rows="8"
            maxlength="1000"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="Interaction" prop="interaction">
          <el-input
            type="textarea"
            placeholder="Please Enter Interaction"
            v-model="formData.interaction"
            rows="8"
            maxlength="1000"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="Neighborhood Overview" prop="neighborhood_overview">
          <el-input
            type="textarea"
            placeholder="Please Enter Neighborhood Overview"
            v-model="formData.neighborhood_overview"
            rows="8"
            maxlength="1000"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="Transit" prop="transit">
          <el-input
            type="textarea"
            placeholder="Please Enter Transit"
            v-model="formData.transit"
            rows="8"
            maxlength="1000"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="Notes" prop="notes">
          <el-input
            type="textarea"
            placeholder="Please Enter Notes"
            v-model="formData.notes"
            rows="8"
            maxlength="1000"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="House Rules" prop="house_rules">
          <el-input
            type="textarea"
            placeholder="Please Enter House Rules"
            v-model="formData.house_rules"
            rows="8"
            maxlength="1000"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item style="text-align: center;">
          <el-button type="primary" @click="doSave">Save Changes</el-button>
          <el-button @click="doReset">Reset Form</el-button>

          <el-button type="danger"  @click="doSynchro">更新房源描述</el-button>

        </el-form-item>

      </el-form>
        </el-scrollbar>
      </div>
</template>

<script>
    import {addModel,searchModel,get,updateModel} from "@/api/model";
    import {submitAction} from "@/api/task";

    export default {
        name: "EditListingDescriptionForm",
        props: ["pid","drawerVisible"],
        data() {
            return {
                model: 'PhysicalRoomListingDescription', //（物理房间列表说明）
                bodyHeight:900,
                loading:false,
                loadingText:'data saving ...',
                localeName: 'English',
                localCache: null,
                formData: this.getInitFormData(),
                rules: this.getInitRules(),
                cacheData:null
            }
        },
        created() {
            const _bodyHeight = document.documentElement.clientHeight || document.body.clientHeight;
           // console.log("bodyHeight="+_bodyHeight);
            this.bodyHeight = _bodyHeight - 65;
        },
        mounted(){
            this.cacheData = {...this.formData};
        },

        methods: {

            getInitFormData(){
                return  {
                    id: null, //ID数据
                    locale:'en', // Enum字符串 对应房源描述的语言。一个PhysicalRoom可以有多个不同locale的描述。
                    physical_room_hook:this.pid,//   Hook    链接到PhysicalRoom的外键
                    name:null,//    字符串 最多60字。房源的标题，会覆盖PhysicalRoomListing中的name
                    summary:null,// 字符串 最多2000字。房源的简介
                    space:null,//   字符串 最多2000字。房源空间的简介
                    access:null,//  字符串 最多2000字。房源内客人可用空间的简介
                    interaction:null,// 字符串 最多2000字。房东与房客互动的简介
                    neighborhood_overview:null,//   字符串 最多2000字。房源周边地区简介
                    transit:null,// 字符串 最多2000字。房源附近公共交通的简介及如何抵达房源
                    notes:null,//   字符串 最多2000字。其他需要房客知道的信息
                    house_rules:null,// 字符串 最多2000字。房屋守则。
                };
            },
            getInitRules(){
                return {
                    locale: [
                        {required: true, message: 'Please select A Property Type Group', trigger: 'change'}
                    ],
                    name: [
                        {required: true, message: 'Please Enter Name', trigger: 'blur'},
                        {min: 2, max: 60, message: '2 to 60 characters in length', trigger: 'blur'}
                    ],
                    summary: [
                        {required: true, message: 'Please Enter Summary', trigger: 'blur'},
                        {min: 2, max: 2000, message: '2 to 2000 characters in length', trigger: 'blur'}
                    ],
                    space: [
                        {required: true, message: 'Please Enter Space', trigger: 'blur'},
                        {min: 2, max: 2000, message: '2 to 2000 characters in length', trigger: 'blur'}
                    ],
                    access: [
                        {required: true, message: 'Please Enter Access', trigger: 'blur'},
                        {min: 2, max: 2000, message: '2 to 2000 characters in length', trigger: 'blur'}
                    ],
                    interaction: [
                        {required: true, message: 'Please Enter Interaction', trigger: 'blur'},
                        {min: 2, max: 2000, message: '2 to 2000 characters in length', trigger: 'blur'}
                    ],
                    neighborhood_overview: [
                        {required: true, message: 'Please Enter Neighborhood Overview', trigger: 'blur'},
                        {min: 2, max: 2000, message: '2 to 2000 characters in length', trigger: 'blur'}
                    ],
                    transit: [
                        {required: true, message: 'Please Enter Transit', trigger: 'blur'},
                        {min: 2, max: 2000, message: '2 to 2000 characters in length', trigger: 'blur'}
                    ],
                    notes: [
                        {required: true, message: 'Please Enter Notes', trigger: 'blur'},
                        {min: 2, max: 2000, message: '2 to 2000 characters in length', trigger: 'blur'}
                    ],
                    house_rules: [
                        {required: true, message: 'Please Enter House Rules', trigger: 'blur'},
                        {min: 2, max: 2000, message: '2 to 2000 characters in length', trigger: 'blur'}
                    ],
                };
            },
            /**
             * 语言切换
             **/
            changeLanguage(val){
              const _this = this;
              let _lng = '';
              switch (val) {
                  case 'Chinese':{
                      _lng = 'zh';
                      break;
                  }  case 'Japanese':{
                      _lng = 'ja';
                      break;
                  }  case 'English':{
                      _lng = 'en';
                      break;
                  }default:{
                      console.error(val+" 无对应的枚举值");
                      break;
                  }
              }
              if((!this.localCache && this.localCache != 'en') && this.formActionType == 'ADD' && _lng != 'en'){
                  this.$message({
                      type: 'info',
                      message: 'When adding data for the first time, you must first save the data in English'
                  });
                  this.localeName = 'English';
                  return;
              }

              console.log("_lng="+_lng+", locale="+this.formData.locale);
              if(_lng == this.localCache) return;

              //----- 当切换为不同语言时要保存之前变动的数据 ---//
                if(!this.checkDataIsChanged()){
                    _this.loadDatas(_lng);
                    return;
                }
                if(confirm('Language changes, please save the current data first')){
                    this.doSave(() => {
                     _this.loadDatas(_lng);
                    });
                }else{
                    _this.loadDatas(_lng);
                }
            },
            checkDataIsChanged(){
               const formDataLength = this.getJsonLength(this.formData);
               const cacheDataLength = this.getJsonLength(this.cacheData);
               if(formDataLength === 0 && cacheDataLength === 0) return false;
               for(let key in this.formData){
                   if(key == 'locale') continue;
                   const _val = this.formData[key];
                   const val = this.cacheData[key];
                   //console.log(key+" = "+val+" , _val = "+ _val);
                   if(val != _val){
                       console.log(key+" = "+val);
                       return true;
                   }
               }
               return false;
            },
            getJsonLength(obj){
                let size = 0;
                for(let key in obj) {
                    if (obj.hasOwnProperty(key)) size++;
                }
                return size;
            },
            refresh(){
                this.localeName = "English";
                this.loadDatas('en');
            },
            loadDatas(_locale){
                let _this = this;
                _this.loading = true;
                this.doReset();
                const _pid = this.pid;
                this.localCache = null;
                this.formData = this.getInitFormData();
                _this.cacheData = {...this.formData};
                searchModel('PhysicalRoomListingDescription', {
                    search_keys:{physical_room__physical_room_id: _pid,locale:_locale}
                }).then(res => {
                    _this.loading = false;
                    console.log(res);
                    const list = res.data.list;
                    _this.localCache = _locale;
                    if(!list || list.length == 0){
                        _this.formData = _this.getInitFormData();
                        _this.formData.locale = _locale;
                        return;
                    }
                    _this.formData = list[0];
                    _this.cacheData = {...list[0]};
                }).catch(reason => {
                    _this.loading = false;
                    console.error(reason);
                });
            },
            /**
             * 保存数据
             */
            doSave(_callback){
                console.log("doSave to do ...");
                console.log("pid="+this.pid);
                const _this = this;
                this.formData.physical_room_hook = this.pid;

                console.log(this.formData);
                let _formData = this.formData;
                for(var key in _formData){
                    const val = _formData[key];
                    if(!val && (val !== 0 || val !== '0')){
                        delete _formData[key];
                    }
                }

                this.$refs['formData'].validate((valid) => {
                    if (valid) {
                        _this.loading = true;
                        if(_this.formData.id){
                            updateModel('PhysicalRoomListingDescription', _this.formData.id, _formData).then(res => {
                                _this.loading = false;
                               // _this.doSynchro();
                                _this.localCache = _this.formData.locale;
                                _this.cacheData = {..._this.formData};
                                _this.$message({
                                    type: 'info',
                                    message: 'Save Data Success!'
                                });
                                if(_callback) _callback();

                            }).catch(reason => {
                                _this.loading = false;
                                console.log("doSave Failure...");
                                console.log(reason);
                                //_this.$message.error('Please Check Input Form Data Has Errors!');
                            });
                        }else{
                            const jsonStr =  JSON.stringify(_formData);
                            addModel('PhysicalRoomListingDescription', jsonStr).then(res => {
                                console.log("id="+res);
                                const _id = res.id;
                                _this.formData.id = _id;
                                _this.loading = false;
                                _this.localCache = _this.formData.locale;
                                _this.cacheData = {..._this.formData};
                                _this.$message({
                                    type: 'info',
                                    message: 'Save Data Success!'
                                });
                                if(_callback) _callback();
                            }).catch(reason => {
                                _this.loading = false;
                                console.log("doSave Failure...");
                                console.log(reason);
                               // _this.$message.error('Please Check Input Form Data Has Errors!');
                            });
                        }
                    } else {
                        console.log('error submit!!');
                        _this.$message.error('Please Check Input Form Data Has Errors!');
                        return false;
                    }
                });
            },
            /**
             * 重置表单
             */
            doReset(){
              this.formData = this.getInitFormData();
              if(this.$refs['formData']) this.$refs['formData'].resetFields();
            },
            /**
             * ActionTask ABNB API 同步
             */
            doSynchro(){
              const _this = this;
              const _id = this.formData.id;
              if(!_id){
                _this.$message.error('PhysicalRoomListingDescription id is null,Please Check Data...!');
                return;
              }
              //create_update_listing_description
              const actionName = "create_update_listing_description";
              this.loadingText = "Calling API: "+actionName+" ...";
              this.loading = true;

              submitAction(this.model, _id,actionName).then(res => {
                this.loading = false;
                _this.$notify({
                  title: 'Success',
                  message: 'PhysicalRoomListingDescription Id:'+ _id +' call API:'+actionName+' succeeded !',
                  type: 'success'
                });

              }).catch(reason => {
                _this.loading = false;
                console.log("deleteModel Failure...");
                console.error(reason);
                let errMsg = reason.data || reason.statusText;

                _this.$notify.error({
                  title: 'Error',
                  message: 'API:'+actionName+'  call error ,Error Reason:['+errMsg+']'
                });
                //_this.$message.error('Please Check Input Form Data Has Errors!');
              });
            }
        }
    }
</script>

<style scoped>
  .form-wrap{
    padding: 0px 20px;
  }
</style>
